﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using websitev2.Models;
using Microsoft.Web.Helpers;

namespace websitev2.Controllers
{
    public class AccountController : Controller
    {

        private Models.StartStopEntities db = new StartStopEntities();
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // Check to see if the user is trying to logon with an email address instead
                if (model.UserName.Contains("@"))
                {
                    string username = Membership.GetUserNameByEmail(model.UserName);
                    if (username != null)
                    {
                        // switch the email address for the actual username.
                        model.UserName = username;
                    }
                }

                // Allow email to drop through to the standard validation to save having to write the same thing twice. 

                if (Membership.ValidateUser(model.UserName, model.Password))
                {

                    // Get the userGUID
                    Guid UserGUID = Guid.Parse(Membership.GetUser(model.UserName).ProviderUserKey.ToString());

                    // next we load the loggedinuser information into the session as we'll be needing it
                    Models.User.LoggedIn oLogged = Core.UserCore.LoadLoggedInUserDetails(UserGUID);
                    // Populate the user session.
                    Session["oLogged"] = oLogged;
                    Session["oUsername"] = oLogged.UserName;

                    // here we should update when the user last logged in
                    try
                    {
                        Core.SqlAccessCore.ExecuteScalar("update ssUsers set LastSeenOnline = GetDate(),LoginCount=(LoginCount+1) where Username = '" + model.UserName + "'");

                    }
                    catch (Exception ex)
                    {
                        Core.EventLog.WriteErrorEvent(ex.Message);
                    }


                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("user", "stats", new { id = model.UserName });
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult RegistrationComplete()
        {



            return View();
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            // Clear the logged session
            Session["oLogged"] = null;


            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {

            return View(new Models.RegisterModel { Newsletter = true });
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(Models.RegisterModel model)
        {
            // Ideally the recapture should be asyncronouse.
            if (!ReCaptcha.Validate(privateKey: "6LesSssSAAAAACI-Gl98AQZLh--PPnM_Q2T-RImO"))
            {
                // Recapture has failed. 
            }
            else
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        // TO DO ASSIGN THE ROLE TO THE USER! 


                        // Attempt to register the user
                        MembershipCreateStatus createStatus;
                        Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                        if (createStatus == MembershipCreateStatus.Success)
                        {
                            FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                            Roles.AddUserToRole(model.UserName, "SiteUser");

                            // This is where we would create the corresponding ssuser model. 
                            ssUser oUser = new ssUser();
                            oUser.UserName = model.UserName;
                            oUser.Password = model.Password;
                            oUser.EmailAddress = model.Email;
                            oUser.UserGUID = Guid.Parse(Membership.GetUser(model.UserName).ProviderUserKey.ToString());
                            oUser.Authenticated = true;
                            oUser.CreatedOn = DateTime.Now;
                            oUser.LoginCount = 1;

                            // This should really be saved under the general prefs! 
                            oUser.Newsletter = model.Newsletter;

                            // Set defaults
                            oUser.Deleted = false;
                            oUser.PrivacySetting = 0;

                            db.ssUsers.AddObject(oUser);
                            db.SaveChanges();

                            // Send an update email; 
                            try
                            {
                                // Send an email so we know a new user has been registered
                                Core.Email.SendPlainEmail("startstop.me@gmail.com", "New users", "A new user has registered ");
                            }
                            catch
                            {
                            }


                            // This is pretty ineffecient, but it's the best we can hope for right now.. makes sure the session variables are all 
                            // populated.
                            // next we load the loggedinuser information into the session as we'll be needing it
                            Models.User.LoggedIn oLogged = Core.UserCore.LoadLoggedInUserDetails(oUser.UserGUID.GetValueOrDefault());
                            // Populate the user session.
                            Session["oLogged"] = oLogged;
                            Session["oUsername"] = oLogged.UserName;

                            // Now save the extended prefs

                            try
                            {
                                if (model.PSNID != "")
                                {
                                    StartStop.ServiceResources.Setting oSetting = new StartStop.ServiceResources.Setting();
                                    oSetting.PreferenceName = "PSNID"; 
                                    oSetting.PreferenceString = model.PSNID;
                                    oSetting.PreferenceType = 1;
                                    oSetting.UserID = oLogged.UserID;
                                    oSetting.CreatedOn = DateTime.Now;
                                    StartStop.Helpers.UserPreferences.SaveUserSetting(oSetting);

                                    try
                                    {
                                        // Add the PSNtask
                                        StartStop.ServiceResources.Tasks oTasks = new StartStop.ServiceResources.Tasks();
                                        oTasks.OtherType = "PSNID";
                                        oTasks.TaskStatus = 1;
                                        oTasks.DataToRun = oSetting.PreferenceString;
                                        
                                        StartStop.Helpers.TaskDespatcher.AddTask(oTasks); 
                                    }
                                    catch (Exception ex)
                                    {
                                        StartStop.ServiceResources.ErrorEvent oError = new StartStop.ServiceResources.ErrorEvent();
                                        oError.CreatedOn = DateTime.Now;
                                        oError.ErrorDetail = ex.Message.ToString();
                                        oError.ErrorFrom = StartStop.ServiceResources.ErrorEvent.ErrorOriginatedFrom.UserSite;
                                        oError.ErrorLevel = StartStop.ServiceResources.ErrorEvent.ErrorLevelType.NotSoCritical;
                                        oError.ErrorMessage = "Cannot save add PSN TASK";


                                        StartStop.Helpers.EventLog.LogError(oError);
                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                StartStop.ServiceResources.ErrorEvent oError = new StartStop.ServiceResources.ErrorEvent();
                                oError.CreatedOn = DateTime.Now;
                                oError.ErrorDetail = ex.Message.ToString();
                                oError.ErrorFrom = StartStop.ServiceResources.ErrorEvent.ErrorOriginatedFrom.UserSite;
                                oError.ErrorLevel = StartStop.ServiceResources.ErrorEvent.ErrorLevelType.NotSoCritical;
                                oError.ErrorMessage = "Cannot save PSN setting in registration";


                                StartStop.Helpers.EventLog.LogError(oError);
                            }

                            try
                            {
                                StartStop.ServiceResources.Setting oSetting = new StartStop.ServiceResources.Setting();
                                oSetting.PreferenceName = "newsletter";
                                oSetting.PreferenceType = 2;
                                oSetting.PreferenceBool = model.Newsletter;
                                oSetting.CreatedOn = DateTime.Now;
                                oSetting.UserID = oLogged.UserID; 
                                StartStop.Helpers.UserPreferences.SaveUserSetting(oSetting);
                            }
                            catch (Exception ex)
                            {
                                StartStop.ServiceResources.ErrorEvent oError = new StartStop.ServiceResources.ErrorEvent();
                                oError.CreatedOn = DateTime.Now;
                                oError.ErrorDetail = ex.Message.ToString();
                                oError.ErrorFrom = StartStop.ServiceResources.ErrorEvent.ErrorOriginatedFrom.UserSite;
                                oError.ErrorLevel = StartStop.ServiceResources.ErrorEvent.ErrorLevelType.NotSoCritical;
                                oError.ErrorMessage = "Cannot save newsletter setting in registration";


                                StartStop.Helpers.EventLog.LogError(oError);
                            }




                            return RedirectToAction("RegistrationComplete", "Account");
                        }
                        else
                        {
                            ModelState.AddModelError("", ErrorCodeToString(createStatus));
                        }
                    }
                } // try catch 
                catch (Exception ex)
                {
                    StartStop.ServiceResources.ErrorEvent oError = new StartStop.ServiceResources.ErrorEvent();
                    oError.CreatedOn = DateTime.Now;
                    oError.ErrorDetail = ex.Message.ToString();
                    oError.ErrorFrom = StartStop.ServiceResources.ErrorEvent.ErrorOriginatedFrom.UserSite;
                    oError.ErrorLevel = StartStop.ServiceResources.ErrorEvent.ErrorLevelType.Critical; 
                    oError.ErrorMessage = "Cannot registration";


                    StartStop.Helpers.EventLog.LogError(oError); 
                }
            } // End of recapture thing

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        [Authorize]
        public ActionResult ManageAccount()
        {
            if (Session["oLogged"] != null)
            {

                Models.User.LoggedIn oLogged = new Models.User.LoggedIn();
                // Populate the user session.
                oLogged = (Models.User.LoggedIn)Session["oLogged"];

                ViewBag.oLogged = oLogged;



                #region load the generic user information
                // This should be refactored into a generic action for all logged in user bits
                
                var user = db.ssUsers.FirstOrDefault(u => u.UserID == oLogged.UserID);
                
                // Load the general information 
                Models.UserGeneralInformationModel oUserGen = new Models.UserGeneralInformationModel();
                oUserGen = websitev2.Core.UserCore.LoadUserGen(user.UserGUID.GetValueOrDefault());
                ViewBag.UserGen = oUserGen;
                ViewBag.MediumAvatar = Core.UserCore.ReturnAvatarURL(user.UserGUID.GetValueOrDefault(), 1);
                #endregion


                // Also we need to check that there aren't any missing preferences
                StartStop.Helpers.UserPreferences.CheckDefaultUserSettings(oLogged.UserID);

                return View(StartStop.Helpers.UserPreferences.ReturnUserSettings(oLogged.UserID));
            }
            else
            {
                return View();

            }
        }

        [HttpPost]
        [Authorize]
        public ActionResult ManageAccount(StartStop.ServiceResources.UserSettings model)
        {
            if (ModelState.IsValid)
            {

                Models.User.LoggedIn oLogged = new Models.User.LoggedIn();
                // Populate the user session.
                oLogged = (Models.User.LoggedIn)Session["oLogged"];
                #region load the generic user information
                // This should be refactored into a generic action for all logged in user bits

                var user = db.ssUsers.FirstOrDefault(u => u.UserID == oLogged.UserID);

                // Load the general information 
                Models.UserGeneralInformationModel oUserGen = new Models.UserGeneralInformationModel();
                oUserGen = websitev2.Core.UserCore.LoadUserGen(user.UserGUID.GetValueOrDefault());
                ViewBag.UserGen = oUserGen;
                ViewBag.MediumAvatar = Core.UserCore.ReturnAvatarURL(user.UserGUID.GetValueOrDefault(), 1);
                #endregion



                foreach (StartStop.ServiceResources.Setting oSetting in model.Settings)
                {
                    // When we run this we need to dress the setting before we shoot it over to the helper


                    // Just add the userID
                    oSetting.UserID = oLogged.UserID;

                    StartStop.Helpers.UserPreferences.SaveUserSetting(oSetting);

                    // Look for any task despatcher which needs to be run 
                    if (oSetting.PreferenceName.ToLower() == "psnid")
                    {
                        // Add the PSNtask
                        StartStop.ServiceResources.Tasks oTasks = new StartStop.ServiceResources.Tasks();
                        oTasks.OtherType = "PSNID";
                        oTasks.TaskStatus = 1;
                        oTasks.DataToRun = oSetting.PreferenceString;
                        StartStop.Helpers.TaskDespatcher.AddTask(oTasks); 
                    }

                }
            }
            return View(model);
        }

    }
}
